package course8.com.youkeda.service.impl;

import course8.com.youkeda.model.CourseTimetable;
import course8.com.youkeda.model.Timetable;
import course8.com.youkeda.model.WeekPlan;
import course8.com.youkeda.service.CourseTimetableService;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CourseTimetableServiceImpl implements CourseTimetableService {
    private static List<CourseTimetable> COURSE_TIMETABLES=new ArrayList<>();

    @Override
    public void invoke(CourseTimetable courseTimetable, LocalDateTime startTime, LocalDateTime endTime, List<WeekPlan> weekPlans) {


        if (courseTimetable.getTimetables() == null) {
            courseTimetable.setTimetables(new ArrayList<>());
        }
        // 根据课时安排课程
        int sections = courseTimetable.getCourse().getSections();
        //得到两个日期的间隔天数
        long days = Duration.between(startTime,endTime).toDays();

        for (int i = 0; i < days; i++) {
            // 如果课程已经分配完了，不用再排课了
            if (sections == 0) {
                break;
            }
            // 使用 plusDays 让日期递增
            LocalDateTime now = startTime.plusDays(i);

            // TODO 根据课程计划来判断这一天是否需要上课，上课的具体时间
            for (WeekPlan week:weekPlans
                 ) {
                if (now.getDayOfWeek().getValue()==week.getWeekDay()){
                    Timetable timetable=new Timetable();
                    timetable.setId(UUID.randomUUID().toString());
                    //默认8点上课
                    LocalDateTime begin = now.withHour(8).withMinute(0);
                    timetable.setStartTime(begin);
                    //如果是下午
                    if (week.getTime().equals("pm")){
                        //设置时间为13.00
                       begin=now.withHour(13).withMinute(0);
                    }
                    timetable.setStartTime(begin);
                    // 每节课耗时一个小时，所以结束时间等于开始时间+几节
                    timetable.setEndTime(begin.plusHours(week.getCount()));
                    courseTimetable.getTimetables().add(timetable);
                    //课时减少
                    sections=sections-week.getCount();
                }

            }

        }
        COURSE_TIMETABLES.add(courseTimetable);
    }

    @Override
    public CourseTimetable queryForClass(String classesid) {
        for (CourseTimetable courseTimetable:COURSE_TIMETABLES
             ) {
            if (courseTimetable.getClasses().getId().equals(classesid)){
                return courseTimetable;
            }
        }
        return null;
    }
}
